﻿using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using log4net;

namespace Objectware.Silverlight.Testing.Runner
{
	public partial class ExecutionForm : Form
	{
		private static readonly ILog logger = Logging.GetLogger<ExecutionForm>();

		private static ExecutionForm _Form;

		private static readonly TestResultService.TestResultService TestResultService =
			ServiceLocator.Default.GetInstance<TestResultService.TestResultService>();

		private static readonly ManualResetEvent _waitEvent;
		private static readonly Thread _MessagePumpThread;

		static ExecutionForm()
		{
			logger.Info("ExecutionForm - start thread");

			_waitEvent = new ManualResetEvent(false);
			_MessagePumpThread = new Thread(ExecutionForm_Thread);
			_MessagePumpThread.SetApartmentState(ApartmentState.STA);
			_MessagePumpThread.Start();
		}

		public ExecutionForm()
		{
			InitializeComponent();

			this.Initialize();

			logger.Info("ExecutionForm CTOR");

		}

		private void Initialize()
		{
			this.Size = new Size(0, 0);
			this.Location = new Point(400000, 400000);
			this.MaximizeBox = false;
			this.HelpButton = false;
			this.ShowIcon = false;
			this.ShowInTaskbar = false;
			this.FormBorderStyle = FormBorderStyle.None;
			this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
			this.BackColor = Color.Transparent;

			//this._webBrowser.Visible = false;
		}

		private static void ExecutionForm_Thread()
		{
			logger.Info("Starting the execution form");

			_Form = new ExecutionForm();

			_waitEvent.Reset();

			Application.Run(_Form);

		}


		public static void RunTests(TestHarness harness)
		{
			logger.Info("RunTests()");

			var methodsString = new StringBuilder();
			foreach (var method in harness.MethodsToTest)
			{
				if( methodsString.Length > 0 ) 
				{
					methodsString.Append("+");
				}
				methodsString.Append(method);
			}

			
			var url = ServerManager.Instance.TestPageUrl + "?TestProject=" + harness.XapFile;
			/*
			var encodedMethodsString = HttpUtility.UrlEncode(methodsString.ToString());
			url += string.Format("&MethodsToTest={0}", encodedMethodsString);
			 * */

			logger.Info(string.Format("RunTests, URL = {0}", url));

			_waitEvent.WaitOne();

			logger.Info("Showing the form");

			_Form.Show();
			_Form._webBrowser.DocumentCompleted +=
				(s, e) =>
					{

						logger.Info("Document loaded - ready to run it all");
						var element = _Form._webBrowser.Document.CreateElement("div");
						element.Id = "MethodsToTest";
						element.InnerText = methodsString.ToString();
						_Form._webBrowser.Document.Body.AppendChild(element);
					};


			_Form._webBrowser.Navigate(url);
		}

	}
}
